<?php

namespace app\common\model\banxi\course;

use app\common\enums\ArticleStatusEnum;
use app\common\enums\ArticleTTlStatusEnum;
use app\common\model\common\BaseModel;
use app\common\service\TencentVocalService;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/*
 * 文章管理
 * */

class CourseArticle extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_course_article';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'statusCn',
        'ttlStatusCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'ttlStatus' => 'string',
        'status' => 'string',
        'courseId' => 'string',
        'sortNum' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                         ｜
    //-----------------------------------------------------------------------------------


    public function getStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        return (new ArticleStatusEnum)->getDescription($value) ?? '';
    }

    public function getTtlStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['ttlStatus'] ?? '');
        return (new ArticleTTlStatusEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //----------------------------------------------------------------------------------

    /**
     * 获取下一章节ID
     * @param int $articleId 当前文章ID
     * @return int|null 下一篇文章ID，如果没有则返回null
     */
    public function getNextId($articleId)
    {
        // 查询当前文章信息
        $courseArticle = $this
            ->where('id', $articleId)
            ->field('sortNum, id, courseId')
            ->find();

        // 如果文章不存在，返回null
        if (empty($courseArticle)) {
            return null;
        }

        // 获取课程ID和排序号
        $courseId = $courseArticle['courseId'];
        $sortNum = $courseArticle['sortNum'];

        // 查询下一章节ID
        $nextId = $this
            ->where('courseId', $courseId)
            ->where('id', '<>', $articleId)
            ->where('sortNum', '>=', $sortNum)
            ->order('sortNum', 'asc')
            ->limit(1)
            ->value('id');

        return $nextId ?: null;
    }

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this
            ->where($where)
            ->order(['sortNum' => 'asc'])
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ]);
    }

    public function getInfo(array $where)
    {
        return $this->where($where)->find();
    }

    public function saveOrUpdate($data)
    {
        $modelId = $data['id'] ?? null;
        if (!$modelId) {
            $isTTl = true;
            $courseArticleRaw = $this;
        } else {
            $courseArticleRaw = $this->where(['id' => $modelId])->find();
            $contentRaw = $courseArticleRaw['content'];
            $content = $data['content'];
            $isTTl = $contentRaw != $content;
        }
        if ($isTTl) {
            $tencentVocalService = new TencentVocalService();
            $ttlTaskId = $tencentVocalService->longTextToVoiceTheStandardAndEn($data['content'], '/common_api/CallBack/ttlCallback?server=1');
            if (!$ttlTaskId) {
                throw new ValidateException($tencentVocalService->getError());
            }
            $data['ttlTaskId'] = $ttlTaskId;
        }
        $courseArticleRaw->save($data);
        return true;
    }

    public function del(array $ids)
    {
        return self::destroy(function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        });
    }

    public function generateAudioFromScratch($data)
    {
        $tencentVocalService = new TencentVocalService();
        $taskStatus = $tencentVocalService->longTextToSpeechResultQuery($data['ttlTaskId']);
        if ($taskStatus->getStatus() == 3 || $taskStatus->getStatus() == 2) {
            $this->saveOrUpdate($data);
        }
        return $taskStatus->getStatusStr();

    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


}